<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>批量查询 - 考试成绩系统</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 配置Tailwind -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#10b981',
                        accent: '#8b5cf6',
                        neutral: '#64748b',
                        success: '#22c55e',
                        warning: '#f59e0b',
                        danger: '#ef4444',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .nav-shadow {
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            }
            .card-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            }
            .input-focus {
                @apply focus:ring-2 focus:ring-primary focus:border-transparent transition-all duration-200;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
    <!-- 导入导航栏模板 -->
    {% include '_navbar.html' %}

    <!-- 主要内容区域 -->
    <main class="container mx-auto px-4 pt-28 pb-16">
        <section class="mb-8">
            <div class="mb-6">
                <h2 class="text-2xl font-bold text-gray-800">批量查询</h2>
                <p class="text-gray-500">请输入成绩查询网址，上传学生名单文件</p>
            </div>

            <!-- 查询表单 -->
            <div class="bg-white rounded-xl card-shadow p-6 mb-6">
                <!-- Flash消息显示 -->
                {% with messages = get_flashed_messages() %}
                    {% if messages %}
                        {% for message in messages %}
                            <div class="mb-4 p-3 bg-yellow-50 text-yellow-700 border border-yellow-300 rounded-md">
                                <i class="fa fa-info-circle mr-2"></i>{{ message }}
                            </div>
                        {% endfor %}
                    {% endif %}
                {% endwith %}
                
                <form action="/batch_query" method="POST" enctype="multipart/form-data">
                    <div class="flex flex-col md:flex-row gap-4">
                        <div class="flex-1">
                            <input 
                                type="text" 
                                id="query_url" 
                                name="query_url" 
                                class="w-full p-3 border border-gray-300 rounded-md focus:outline-none input-focus" 
                                placeholder="请输入成绩查询网址..."
                            >
                        </div>
                        <div>
                            <label for="student_file"  class="inline-flex items-center px-4 py-3 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors cursor-pointer border border-gray-300">
                                <i class="fa fa-upload mr-2"></i>
                                <span>上传学生名单</span>
                                <input type="file" id="student_file" name="student_file" class="hidden" accept=".xlsx,.xls">
                            </label>
                        </div>
                        <div>
                            <button id="query-button" type="button" class="px-6 py-3 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors flex items-center space-x-2">
                                <i class="fa fa-search"></i>
                                <span>查询</span>
                            </button>
                        </div>
                    </div>
                </form>
                
                <!-- 查询加载状态 -->
                <div id="loading-indicator" class="hidden mt-4 flex justify-center items-center">
                    <div class="p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <div class="flex items-center space-x-3">
                            <i class="fa fa-spinner fa-spin text-primary text-xl"></i>
                            <span>正在查询成绩，请稍候...</span>
                        </div>
                    </div>
                </div>
            </div>


            <!-- 查询结果表格 -->
            {% if results %}
            <div class="bg-white rounded-xl card-shadow p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">{{ project['name'] }}({{ project['url'] }})</h3>
                    
                    <div class="flex space-x-3">
                        <button id="save-results" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors duration-200 flex items-center">
                            <i class="fa fa-download mr-2"></i> 保存结果
                        </button>
                        <button id="reset-results" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors duration-200 flex items-center">
                            <i class="fa fa-refresh mr-2"></i> 重置
                        </button>
                    </div>
                    
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full table-auto divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                {% for header in table_headers %}
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    {{ header }}
                                </th>
                                {% endfor %}
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            {% for row in table_data %}
                            <tr>
                                {% for cell in row %}
                                <td class="px-4 py-3 text-sm text-gray-500">
                                    {{ cell }}
                                </td>
                                {% endfor %}
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
            {% endif %}
        </section>
    </main>

    <script>
        // 移动端菜单切换
        document.addEventListener('DOMContentLoaded', function() {
            const mobileMenuButton = document.getElementById('mobile-menu-button');
            const mobileMenu = document.getElementById('mobile-menu');
            
            if (mobileMenuButton && mobileMenu) {
                mobileMenuButton.addEventListener('click', function() {
                    mobileMenu.classList.toggle('hidden');
                });
            }
            
            // 绑定结果按钮事件
            function bindResultButtonsEvents() {
                // 保存结果按钮
                const saveButton = document.getElementById('save-results');
                if (saveButton) {
                    saveButton.addEventListener('click', function() {
                        // 获取表头和数据
                        const headers = Array.from(document.querySelectorAll('table thead th')).map(th => th.textContent.trim());
                        const rows = document.querySelectorAll('table tbody tr');
                        
                        // 构建scores数组
                        const scores = [];
                        rows.forEach(row => {
                            const cells = Array.from(row.querySelectorAll('td')).map(td => td.textContent.trim());
                            const scoreData = {};
                            headers.forEach((header, index) => {
                                scoreData[header] = cells[index];
                            });
                            scores.push(scoreData);
                        });
                        
                        // 获取project信息
                        const projectHeader = document.querySelector('h3.text-lg');
                        let projectName = '';
                        let projectUrl = '';
                        
                        if (projectHeader && projectHeader.textContent.includes('(') && projectHeader.textContent.includes(')')) {
                            // 从标题中提取项目名和URL
                            projectName = projectHeader.textContent.split('(')[0].trim();
                            projectUrl = projectHeader.textContent.match(/\(([^)]+)\)/)[1];
                        }
                        
                        // 构建完整的数据字典
                        const dataToSend = {
                            project_name: projectName,
                            project_url: projectUrl,
                            scores: scores
                        };
                        
                        // 显示加载状态
                        saveButton.disabled = true;
                        saveButton.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 保存中...';
                        
                        // 发送数据到服务器
                        fetch('/admin/save_scores', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(dataToSend)
                        })
                        .then(response => response.json())
                        .then(data => {
                            // 恢复按钮状态
                            saveButton.disabled = false;
                            saveButton.innerHTML = '<i class="fa fa-download mr-2"></i> 保存结果';
                            
                            // 显示成功或失败消息
                            if (data.success) {
                                showSaveSuccess(data.message);
                            } else {
                                showSaveError(data.message || '保存失败');
                            }
                        })
                        .catch(error => {
                            // 恢复按钮状态
                            saveButton.disabled = false;
                            saveButton.innerHTML = '<i class="fa fa-download mr-2"></i> 保存结果';
                            
                            console.error('保存失败:', error);
                            showSaveError('保存过程中出现错误，请重试');
                        });
                    });
                }
                
                // 重置按钮
                const resetButton = document.getElementById('reset-results');
                if (resetButton) {
                    resetButton.addEventListener('click', function() {
                        if (confirm('确定要重置查询结果吗？')) {
                            // 清空查询URL
                            document.getElementById('query_url').value = '';
                            
                            // 重置文件输入
                            document.getElementById('student_file').value = '';
                            
                            // 清空文件预览
                            const previewContainer = document.getElementById('file-preview-container');
                            if (previewContainer) {
                                previewContainer.innerHTML = '<p class="text-gray-500">未选择文件</p>';
                            }
                            
                            // 刷新页面以清除结果
                            window.location.reload();
                        }
                    });
                }
            }
            
            // 初始绑定结果按钮事件
            bindResultButtonsEvents();
            
            // 查询按钮加载状态功能
            const queryButton = document.getElementById('query-button');
            const queryForm = queryButton.closest('form');
            const loadingIndicator = document.getElementById('loading-indicator');
            const studentFileInput = document.getElementById('student_file');
            const filePreviewContainer = document.getElementById('file-preview-container');
            
            if (queryButton) {
                queryButton.addEventListener('click', function() {
                    // 获取表单数据
                    const queryUrl = document.getElementById('query_url').value;
                    const studentFile = studentFileInput.files[0];
                    
                    // 验证表单
                    if (!queryUrl) {
                        alert('请输入成绩查询网址');
                        return;
                    }
                    
                    if (!studentFile) {
                        alert('请上传学生名单文件');
                        return;
                    }
                    
                    // 显示加载状态
                    queryButton.disabled = true;
                    queryButton.innerHTML = '<i class="fa fa-spinner fa-spin"></i> <span>查询中...</span>';
                    loadingIndicator.classList.remove('hidden');
                    
                    // 创建FormData对象
                    const formData = new FormData(queryForm);
                    
                    // 使用fetch API提交表单
                    fetch('/batch_query', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.text())
                    .then(html => {
                        // 替换页面内容（保留导航栏）
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(html, 'text/html');
                        const newMain = doc.querySelector('main');
                        const currentMain = document.querySelector('main');
                        
                        if (newMain && currentMain) {
                            currentMain.innerHTML = newMain.innerHTML;
                            
                            // 重新绑定事件监听器
                            bindResultButtonsEvents();
                        }
                          
                    })
                    .catch(error => {
                        console.error('查询失败:', error);
                        alert('查询过程中出现错误，请重试');
                        
                        // 恢复按钮状态
                        queryButton.disabled = false;
                        queryButton.innerHTML = '<i class="fa fa-search"></i> <span>查询</span>';
                        loadingIndicator.classList.add('hidden');
                    });
                });
            }
            
            if (studentFileInput) {
                studentFileInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        // 创建FormData对象
                        const formData = new FormData();
                        formData.append('student_file', file);
                        
                        // 显示加载状态
                        showFilePreviewLoading();
                        
                        // 发送AJAX请求到服务器进行文件上传
                        fetch('/check_file', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            // 隐藏加载状态
                            hideFilePreviewLoading();
                            
                            if (data.success) {
                                // 显示上传成功提示
                                showUploadSuccess(data.message);
                            } else {
                                // 显示错误消息
                                showUploadError(data.message || '文件上传失败');
                            }
                        })
                        .catch(error => {
                            // 隐藏加载状态
                            hideFilePreviewLoading();
                            // 显示错误消息
                            showFilePreviewError('文件上传错误: ' + error.message);
                        });
                    } else {
                        // 如果没有选择文件，隐藏预览
                        if (filePreviewContainer) {
                            filePreviewContainer.style.display = 'none';
                        }
                    }
                });
            }
            
            // 显示上传加载状态
            function showFilePreviewLoading() {
                let uploadContainer = document.getElementById('upload-status-container');
                if (!uploadContainer) {
                    uploadContainer = document.createElement('div');
                    uploadContainer.id = 'upload-status-container';
                    uploadContainer.className = 'mt-2';
                    
                    // 插入到输入框下方
                    const queryUrlInput = document.getElementById('query_url');
                    queryUrlInput.parentNode.appendChild(uploadContainer);
                }
                
                uploadContainer.innerHTML = `
                    <div class="flex items-center py-2">
                        <i class="fa fa-spinner fa-spin text-primary mr-3"></i>
                        <span>正在上传文件，请稍候...</span>
                    </div>
                `;
                uploadContainer.style.display = 'block';
            }
            
            // 隐藏加载状态
            function hideFilePreviewLoading() {
                // 这个函数会在显示结果或错误时自动处理
            }
            
            // 显示上传成功提示
            function showUploadSuccess(message) {
                let uploadContainer = document.getElementById('upload-status-container');
                if (!uploadContainer) {
                    uploadContainer = document.createElement('div');
                    uploadContainer.id = 'upload-status-container';
                    uploadContainer.className = 'mt-2';
                    
                    // 插入到输入框下方
                    const queryUrlInput = document.getElementById('query_url');
                    queryUrlInput.parentNode.appendChild(uploadContainer);
                }
                
                uploadContainer.innerHTML = `
                    <div class="p-3 bg-green-50 text-green-700 border border-green-300 rounded-md">
                        <div class="flex items-center">
                            <i class="fa fa-check-circle text-green-500 mr-3"></i>
                            <p>${message}</p>
                        </div>
                    </div>
                `;
                uploadContainer.style.display = 'block';
            }
            
            // 显示上传错误
            function showUploadError(message) {
                let uploadContainer = document.getElementById('upload-status-container');
                if (!uploadContainer) {
                    uploadContainer = document.createElement('div');
                    uploadContainer.id = 'upload-status-container';
                    uploadContainer.className = 'mt-2';
                    
                    // 插入到输入框下方
                    const queryUrlInput = document.getElementById('query_url');
                    queryUrlInput.parentNode.appendChild(uploadContainer);
                }
                
                uploadContainer.innerHTML = `
                    <div class="p-3 bg-red-50 text-red-700 border border-red-300 rounded-md">
                        <i class="fa fa-exclamation-circle mr-3"></i>${message}
                    </div>
                `;
                uploadContainer.style.display = 'block';
            }
            
            // 显示保存成功提示
            function showSaveSuccess(message) {
                let saveContainer = document.getElementById('save-status-container');
                if (!saveContainer) {
                    saveContainer = document.createElement('div');
                    saveContainer.id = 'save-status-container';
                    saveContainer.className = 'mt-4';
                    
                    // 插入到表格上方
                    const tableContainer = document.querySelector('.overflow-x-auto');
                    tableContainer.parentNode.insertBefore(saveContainer, tableContainer);
                }
                
                saveContainer.innerHTML = `
                    <div class="p-3 bg-green-50 text-green-700 border border-green-300 rounded-md">
                        <div class="flex items-center">
                            <i class="fa fa-check-circle text-green-500 mr-3"></i>
                            <p>${message}</p>
                        </div>
                    </div>
                `;
                saveContainer.style.display = 'block';
                
                // 3秒后隐藏提示
                setTimeout(() => {
                    if (saveContainer) {
                        saveContainer.style.display = 'none';
                    }
                }, 3000);
            }
            
            // 显示保存错误提示
            function showSaveError(message) {
                let saveContainer = document.getElementById('save-status-container');
                if (!saveContainer) {
                    saveContainer = document.createElement('div');
                    saveContainer.id = 'save-status-container';
                    saveContainer.className = 'mt-4';
                    
                    // 插入到表格上方
                    const tableContainer = document.querySelector('.overflow-x-auto');
                    tableContainer.parentNode.insertBefore(saveContainer, tableContainer);
                }
                
                saveContainer.innerHTML = `
                    <div class="p-3 bg-red-50 text-red-700 border border-red-300 rounded-md">
                        <i class="fa fa-exclamation-circle mr-3"></i>${message}
                    </div>
                `;
                saveContainer.style.display = 'block';
            }
        });
    </script>
</body>
</html>